"""搜索工具模块 - 提供网络搜索功能。"""

from typing import Annotated, Any, Optional, cast

from dotenv import find_dotenv, load_dotenv
# 更新导入以使用新的包
try:
    from langchain_tavily import TavilySearchResults
except ImportError:
    # 如果新包不可用，回退到旧包
    from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import InjectedToolArg, tool

# 导入配置将在后续步骤中更新
# from agents.configurations import Configuration

_: bool = load_dotenv(find_dotenv())


@tool(parse_docstring=True)
async def search(
    query: str, *, config: Annotated[RunnableConfig, InjectedToolArg]
) -> Optional[list[dict[str, Any]]]:
    """Search for general web results.

    Args:
      query: The query to search for.

    This function performs a search using the Tavily search engine, which is designed
    to provide comprehensive, accurate, and trusted results. It's particularly useful
    for finding information on a wide range of topics.
    """
    # 临时使用默认配置，后续将更新为统一配置
    max_search_results = 5
    wrapped = TavilySearchResults(max_results=max_search_results)
    result = await wrapped.ainvoke({"query": query})
    return cast(list[dict[str, Any]], result)